﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FileManagerBase;
using FileManagerLibrary.Base;
using System.Windows.Forms;
using System.IO;
using Logging;
using FileManagerLibrary.Base.FileBase;
using FileManagerLibrary.Base.UIData;

namespace FileManagerTool
{
    public class FileManagerController : BackupJobManagerControllerBase
    {
        public FileManagerController(BackupJobManagerView view, BackupJob currentJob, bool isEditMode)
            : base(view, currentJob , isEditMode)
        {
            View.cmbSizeType.Items.AddRange(Enum.GetNames(typeof(FileSizeTypeEnum)));
            View.cmbSizeType.SelectedIndex = 0;
            View.cmbWeek1.SelectedIndex = 0;
            View.cmbMonth1.SelectedIndex = 0;
            View.cmbMultipleCopies.SelectedIndex = 0;
        }

        public override bool SaveData()
        {
            if (ValidateContents(LevelsEnum.Final) == false)
                return false;
            CurrentJob.CurrentBackupJobMode = BackupJobModeEnum.Files;
            CurrentJob.JobSetName = View.txtBackupSetName1.Text;
            CurrentJob.FileSettings.FileNames.Clear();
            CurrentJob.FileSettings.FileNames.AddRange(View.lstFileNames.Items.Cast<string>());
            if (View.rdoCopy1.Checked == true)
                CurrentJob.JobFileOperationMode = JobFilesOperationModeEnum.Copy;
            if (View.rdoMove1.Checked == true)
                CurrentJob.JobFileOperationMode = JobFilesOperationModeEnum.Move;
            if (View.rdoDelete1.Checked == true)
                CurrentJob.JobFileOperationMode = JobFilesOperationModeEnum.Delete;
            CurrentJob.BackupAfterDays = (int)View.numDays1.Value;
            CurrentJob.BackupAfterHours = (int)View.numHours1.Value;
            if (View.rdoDay1.Checked == true)
            {
                CurrentJob.ServiceCheckMode = ServiceIntervalEnum.Daily;
                CurrentJob.ServiceTriggerDayInterval = View.cmbWeek1.SelectedIndex;
                CurrentJob.ServiceTriggerTimeInterval = View.dtpMntDay1.Value;
            }
            else if (View.rdoWeek1.Checked == true)
            {
                CurrentJob.ServiceCheckMode = ServiceIntervalEnum.Weekly;
                CurrentJob.ServiceTriggerDayInterval = View.cmbWeek1.SelectedIndex;
                CurrentJob.ServiceTriggerTimeInterval = View.dtpMntDay1.Value;
            }
            else if (View.rdoMonth1.Checked == true)
            {
                CurrentJob.ServiceCheckMode = ServiceIntervalEnum.Monthly;
                CurrentJob.ServiceTriggerDayInterval = View.cmbMonth1.SelectedIndex;
                CurrentJob.ServiceTriggerTimeInterval = View.dtpMntDay1.Value;
            }
            else if (View.rdoModified.Checked == true)
            {
                CurrentJob.ServiceCheckMode = ServiceIntervalEnum.OnFileUpdated;
                CurrentJob.FileSettings.WaitSecondsOnFileChange = (int)View.numWaitMin.Value;
            }
            if (View.chkFileSizeExceeded.Checked == true)
            {
                CurrentJob.FileSettings.FileSizeCheckEnabled = true;
                CurrentJob.FileSettings.MaxFileSize = (int)View.numExceedsize.Value;
                CurrentJob.FileSettings.MaxFileSizeType = (FileSizeTypeEnum)Enum.Parse(typeof(FileSizeTypeEnum), View.cmbSizeType.SelectedItem.ToString());
            }
            if (View.rdoCopy1.Checked == true)
                CurrentJob.JobFileOperationMode = JobFilesOperationModeEnum.Copy;
            if (View.rdoMove1.Checked == true)
                CurrentJob.JobFileOperationMode = JobFilesOperationModeEnum.Move;
            if (View.rdoDelete1.Checked == true)
                CurrentJob.JobFileOperationMode = JobFilesOperationModeEnum.Delete;
            CurrentJob.FileSettings.MaxVersions = ((int)View.cmbMultipleCopies.SelectedIndex) + 1;
            CurrentJob.RootBackupFolder = View.OriginalRootBackUpFolder;
            if (View.chkFileSizeExceeded.Checked == true)
            {
                CurrentJob.FileSettings.FileSizeCheckEnabled = true;
                CurrentJob.FileSettings.MaxFileSize = (int)View.numExceedsize.Value;
                CurrentJob.FileSettings.MaxFileSizeType = (FileSizeTypeEnum)View.cmbSizeType.SelectedItem;
            }
            else
                CurrentJob.FolderSettings.FileCheckMode = FileCheckModeEnum.ByModifiedDate;
            return true;
        }

        public override void ReloadData()
        {
            View.txtBackupSetName1.Text = CurrentJob.JobSetName;
            View.OriginalRootBackUpFolder = CurrentJob.RootBackupFolder;
            View.lstFileNames.Items.Clear();
            View.lstFileNames.Items.AddRange(CurrentJob.FileSettings.FileNames.ToArray<string>());
            View.numDays1.Value = CurrentJob.BackupAfterDays;
            View.numHours1.Value = CurrentJob.BackupAfterHours;
            View.cmbWeek1.SelectedIndex = CurrentJob.ServiceTriggerDayInterval;
            View.cmbMonth1.SelectedIndex = CurrentJob.ServiceTriggerDayInterval;
            View.cmbMultipleCopies.SelectedIndex = CurrentJob.FileSettings.MaxVersions - 1;
            if(IsEditMode == true)
                View.txtbckLocation1.Text = FileOperations.GetRootBackupDestinationFolder(CurrentJob);
            if (CurrentJob.JobFileOperationMode == JobFilesOperationModeEnum.Move)
                View.rdoMove1.Checked = true;
            if (CurrentJob.JobFileOperationMode == JobFilesOperationModeEnum.Copy)
                View.rdoCopy1.Checked = true;
            if (CurrentJob.JobFileOperationMode == JobFilesOperationModeEnum.Delete)
                View.rdoDelete1.Checked = true;
            if (CurrentJob.ServiceCheckMode == ServiceIntervalEnum.Daily)
            {
                View.rdoDay1.Checked = true;
                View.dtpMntDay1.Value = CurrentJob.ServiceTriggerTimeInterval;
            }
            else if (CurrentJob.ServiceCheckMode == ServiceIntervalEnum.Weekly)
            {
                View.rdoWeek1.Checked = true;
                View.cmbWeek1.SelectedIndex = CurrentJob.ServiceTriggerDayInterval;
                View.dtpMntDay1.Value = CurrentJob.ServiceTriggerTimeInterval;
            }
            else if (CurrentJob.ServiceCheckMode == ServiceIntervalEnum.Monthly)
            {
                View.rdoMonth1.Checked = true;    
                View.cmbMonth1.SelectedIndex  = CurrentJob.ServiceTriggerDayInterval;
                View.dtpMntDay1.Value = CurrentJob.ServiceTriggerTimeInterval;
            }
            else if (CurrentJob.ServiceCheckMode == ServiceIntervalEnum.OnFileUpdated)
            {
                View.rdoModified.Checked = true;
                View.numWaitMin.Value = CurrentJob.FileSettings.WaitSecondsOnFileChange;
            }
            if (CurrentJob.FileSettings.FileSizeCheckEnabled == true)
            {
                View.chkFileSizeExceeded.Checked = true;
                View.numExceedsize.Value = CurrentJob.FileSettings.MaxFileSize;
                View.cmbSizeType.SelectedIndex = View.cmbSizeType.Items.IndexOf(CurrentJob.FileSettings.MaxFileSizeType.ToString());
            }
            if (CurrentJob.JobFileOperationMode == JobFilesOperationModeEnum.Copy)
                View.rdoCopy1.Checked = true;
            if (CurrentJob.JobFileOperationMode == JobFilesOperationModeEnum.Move)
                View.rdoMove1.Checked = true;
            if (CurrentJob.JobFileOperationMode == JobFilesOperationModeEnum.Delete)
                View.rdoDelete1.Checked = true;
        }

        public override bool ValidateContents(LevelsEnum level)
        {
            if (level == LevelsEnum.Level2)
                return true;
            if (View.txtBackupSetName1.Text.Length == 0)
            {
                MessageBox.Show("Enter a Job Name.");
                return false;
            }
            if (View.lstFileNames.Items.Count == 0)
            {
                MessageBox.Show("At least one file name is required.");
                return false;
            }
            if (level == LevelsEnum.Level1)
                return true;
            if (View.rdoCopy1.Checked == true || View.rdoMove1.Checked == true)
            {
                if (View.txtbckLocation1.Text == "")
                {
                    MessageBox.Show("Destination folder required. Cannot proceed.");
                    return false;
                }
            }
            return true;
        }

        internal void HandleOnFileScheduleModeChanged()
        {
            if (View.rdoMonth1.Checked == true)
            {
                View.cmbWeek1.Visible = false;
                View.cmbWeek1.Enabled = false;
                View.cmbMonth1.Visible = true;
                View.cmbMonth1.Enabled = true;
                View.dtpMntDay1.Enabled = true;
                View.numDays1.Enabled = true;
                View.numHours1.Enabled = true;
                View.numWaitMin.Enabled = false;
                View.lblWaitMin.Enabled = true;
            }
            else if (View.rdoWeek1.Checked == true)
            {
                View.cmbWeek1.Visible = true;
                View.cmbWeek1.Enabled = true;
                View.cmbMonth1.Visible = false;
                View.cmbMonth1.Enabled = false;
                View.dtpMntDay1.Enabled = true;
                View.numDays1.Enabled = true;
                View.numHours1.Enabled = true;
                View.numWaitMin.Enabled = false;
                View.lblWaitMin.Enabled = false;
            }
            else if (View.rdoDay1.Checked == true)
            {
                View.cmbWeek1.Visible = false;
                View.cmbWeek1.Enabled = false;
                View.cmbMonth1.Visible = true;
                View.cmbMonth1.Enabled = false;
                View.dtpMntDay1.Enabled = true;
                View.numDays1.Enabled = true;
                View.numHours1.Enabled = true;
                View.numWaitMin.Enabled = false;
                View.lblWaitMin.Enabled = false;
            }
            else if(View.rdoModified.Checked == true)
            {
                View.cmbWeek1.Visible = true;
                View.cmbWeek1.Enabled = false;
                View.cmbMonth1.Visible = false;
                View.cmbMonth1.Enabled = false;
                View.dtpMntDay1.Enabled = false;
                View.numDays1.Enabled = false;
                View.numHours1.Enabled = false;
                View.numWaitMin.Enabled = true;
                View.lblWaitMin.Enabled = true;
            }
        }

        internal void HandleOnFileSizeExceedChanged()
        {
            if (View.chkFileSizeExceeded.Checked == true)
            {
                View.numExceedsize.Enabled = true;
                View.cmbSizeType.Enabled = true;
            }
            else
            {
                View.numExceedsize.Enabled = false;
                View.cmbSizeType.Enabled = false;
            }
        }

        internal int validated;
        internal void HandleOnFileOperationModeChanged(object sender)
        {
            if (validated > 0)
            {
                validated--;
                return;
            }
            if (View.IsUILoading == false)
            {
                if (View.rdoMove1.Checked == true || View.rdoDelete1.Checked == true)
                {
                    if (MessageBox.Show("This will delete the files from the source location. Continue?", "Delete Files", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    {
                        validated = 2; // to cancel one uncheck and one check
                        ((RadioButton)sender).Checked = true;
                        validated++; // to cancel the above check
                    }
                    else
                    {
                        validated++;
                    }
                }
            }
            if (View.rdoCopy1.Checked == true || View.rdoMove1.Checked == true)
            {
                View.lblBackupLocation1.Visible = true;
                View.txtbckLocation1.Visible = true;
                View.btnbckLocation1.Visible = true;
                View.btnCopyCliptoDestination1.Visible = true;
                View.cmbMultipleCopies.Enabled = true;
            }
            else
            {
                View.lblBackupLocation1.Visible = false;
                View.txtbckLocation1.Visible = false;
                View.btnbckLocation1.Visible = false;
                View.btnCopyCliptoDestination1.Visible = false;
                View.cmbMultipleCopies.Enabled = false;
            }
        }

        internal void HndlAddFiles()
        {
            string[] path = FileOperations.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
            if( path==null || path.Length == 0)
                return;
            List<String> files = new List<String>();
            files.AddRange(path);
            AddFilestoList(files);
        }

        internal void HndlCopyfrmClipBoard()
        {
            FileSystemCollection flcol = GetFileSystemListFromClipBoard();
            AddFilestoList(flcol.Files);
        }

        bool AddFilestoList(List<String> files)
        {
            bool FilesSkipped=false;
            if (files == null)
                return false;
            if (files.Count == 0)
                return false;
            foreach (var item in files)
            {
                if (File.Exists(item) == true || Directory.Exists(item))
                    if (FileNameExistsInList(item) == false)
                        View.lstFileNames.Items.Add(item);
                    else
                        FilesSkipped = true;
            }
            if (FilesSkipped == true)
            {
                MessageBox.Show("Some files where skipped to avoid duplicates in destination. Create another job with a different destination folder for the skipped files.");
                return false;
            }
            else
                return false;
        }

        bool FileNameExistsInList(string filename)
        {
            FileInfo fl = new FileInfo(filename);
            foreach (string item in View.lstFileNames.Items)
            {
                if (item.EndsWith(fl.Name))
                {
                    Logger.StaticLogger.AddAuditLogEntry("Warning: " + filename + " has been removed from adding to the list to avoid creating duplicates.");
                    return true;
                }
            }
            return false;
        }

        internal void HndlbtnCopyCliptoDestination1Click()
        {
            string tmp = GetDirectoryFromClipBoard();
            if (tmp != "")
            {
                View.OriginalRootBackUpFolder = tmp;
                View.txtbckLocation1.Text = GetDirectoryFromClipBoard();
            }
        }

        internal void HndlbtnbckLocationClick()
        {
            //in case of file job It would be good if we do not make the default folder as it will definitly create problems for folder job wsith duplicate.
            string temproot = GetBackupLocation(View.OriginalRootBackUpFolder);
            if (temproot != "")
            {
                View.txtbckLocation1.Text = FileOperations.GetRootBackupDestinationFolder(temproot, "", "", CurrentJob.JobGUID,BackupJobModeEnum.Files); //pass second and third parameter "" will tell it is to tell called method this is file mode.
                View.OriginalRootBackUpFolder = temproot;
            }
        }
    }
}
